package com.starsky.common.framework.expect.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.starsky.common.framework.expect.config.LogConfig;
import com.starsky.common.framework.expect.model.AspectLoggerDto;
import com.starsky.common.framework.expect.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description TODO 公共基础服务实现
 */
@Slf4j
@Component
public class LogServiceImpl implements LogService {

    @Autowired
    private LogConfig logConfig;

    /**
     * 发送不需要返回
     */
    public static void sendLog(String url, Object obj) {
        // 开始处理http请求信息
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entityParams = new StringEntity(JSONObject.toJSONString(obj), "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            // 设置超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000) // 设置连接超时时间，单位毫秒。
                    // .setConnectionRequestTimeout(1000) 设置从connectManager获取Connection超时时间，单位毫秒
                    // .setSocketTimeout(5000) 请求获取数据的超时时间，单位毫秒。如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用
                    .build();
            httpPost.setConfig(requestConfig);
            client = HttpClients.createDefault();
            client.execute(httpPost);
        } catch (Exception e) {
            log.error("*******************日志记录发送，错误信息***************", e);
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                log.error("*******************日志记录发送，错误信息***************", e);
                e.printStackTrace();
            }
        }
    }

    @Override
    public void sendLog(String reqUrl, AspectLoggerDto ald, int logType) {

        if (StringUtils.isBlank(logConfig.getAppNo()) ||
                !logConfig.getLogAsync() ||
                StringUtils.isBlank(logConfig.getLogAsyncUrl()) ||
                !logConfig.getLogAsyncUrl().toLowerCase().startsWith("http")
        ) {
            log.info("logconfig 属性(AppNo/LogAsync/LogAsyncUrl)不能为空");
            return;
        }
        // 保存日志的地址不在发送日志保存接口
        if (StringUtils.isBlank(reqUrl)) {
            log.info("请求路径reqUrl不能空");
            return;
        }
        // //1-操作日志保存；2-系统异常日志；3-业务异常日志；4-登陆日志
        String url = logConfig.getLogAsyncUrl();
        ald.setAppNo(logConfig.getAppNo());
        String userId = ald.getUserId();
        // 执行发送
        sendLog(url, ald);
    }

}
